package com.woniuxy.health.commodity.listener;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.health.commodity.dto.GoodsDTO;
import com.woniuxy.health.commodity.service.impl.GoodsServiceImpl;
import com.woniuxy.health.commodity.service.impl.GoodsTypeServiceImpl;
import com.woniuxy.health.model.commodity.Goods;
import com.woniuxy.health.vo.GoodsVO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

// 预热数据
@Component
public class InitData2CacheListener implements CommandLineRunner {

    private final ElasticsearchRestTemplate esTemplate;
    private final GoodsTypeServiceImpl goodsTypeService;
    private final GoodsServiceImpl goodsService;
    private final StringRedisTemplate redisTemplate;

    public InitData2CacheListener(ElasticsearchRestTemplate esTemplate, GoodsTypeServiceImpl goodsTypeService, GoodsServiceImpl goodsService, StringRedisTemplate redisTemplate) {
        this.esTemplate = esTemplate;
        this.goodsTypeService = goodsTypeService;
        this.goodsService = goodsService;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
        // 预热父品类
        goodsTypeService.getAllLevelOne();

        // 把商品数据存储到es
        GoodsDTO goodsDTO = new GoodsDTO();
        goodsDTO.setPageNum(1);
        goodsDTO.setPageSize(Integer.MAX_VALUE);
        Page pageInfo = goodsService.getPageInfo(goodsDTO);
        List<GoodsVO> records = pageInfo.getRecords();

        esTemplate.save(records);

        // 预热库存
//        List<Goods> list = goodsService.list(); // 查询所有书籍对象
//        for (Goods goods : list) {
//                redisTemplate.opsForHash().put("StoreCount", "" + goods.getId(), goods.getGoodsStorecount());
//        }
    }
}
